<?php
declare (strict_types=1);

namespace app\service\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use app\model\DbSource as Model;
use PDO, PDOException;

class DbSource extends BaseController
{
    /**
     * 列表查询
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(Request $request)
    {
        $params = $request->param();
        $page   = isset($params['page']) ? $params['page'] : 1;
        $limit  = isset($params['limit']) ? $params['limit'] : 10;
        $where  = [
            ['delete_time', '=', 0]
        ];
        if (isset($params['code']) && !empty($params['code'])) {
            $where[] = ['code', 'like', "%{$params['code']}%"];
        }
        if (isset($params['name']) && !empty($params['name'])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }
        if (isset($params['type']) && !empty($params['type'])) {
            $where[] = ['name', '=', "{$params['type']}"];
        }
        $pageLimit = [
            'page'      => $page,
            'list_rows' => $limit,
        ];
        $paginate  = Model::where($where)
            ->order('id', 'desc')
            ->paginate($pageLimit);
        return $this->pageData($paginate);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 平台添加
     *
     * @param Request $request
     * @return \think\response\Json
     */
    public function save(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'code'     => 'require',
            'name'     => 'require',
            'type'     => 'require',
            'host'     => 'require',
            'port'     => 'require',
            'dbname'   => 'require',
            'username' => 'require',
            'password' => 'require',
        ], [
            'code.require'     => '代码不能为空',
            'name.require'     => '名称不能为空',
            'type.require'     => '数据库类型不能为空',
            'host.require'     => '连接地址不能为空',
            'port.require'     => '端口不能为空',
            'dbname.require'   => '数据库名不能为空',
            'username.require' => '用户名不能为空',
            'password.require' => '密码不能为空',
        ]);
        $otherData = Model::where('code', $params['code'])->find();
        if ($otherData) {
            return $this->error('您所填写的代码已经存在');
        }
        $data   = [
            'code'        => $params['code'],
            'name'        => $params['name'],
            'type'        => $params['type'],
            'host'        => $params['host'],
            'port'        => $params['port'],
            'dbname'      => $params['dbname'],
            'username'    => $params['username'],
            'password'    => $params['password'],
            'charset'     => $params['charset'],
            'remark'      => $params['remark'],
            'add_time'    => $request->time(),
            'delete_time' => 0,
        ];
        $model  = new Model();
        $result = $model->save($data);
        if (!$result) {
            return $this->error();
        }
        return $this->success();
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $dataModel = Model::find($id);
        if (!$dataModel || $dataModel->delete_time != 0) {
            return $this->error('您所要查询的信息不存在！');
        }
        return $this->repData($dataModel);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 更新平台信息
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $params = $request->param();
        $this->validate($params, [
            'name'     => 'require',
            'type'     => 'require',
            'host'     => 'require',
            'port'     => 'require',
            'dbname'   => 'require',
            'username' => 'require',
            'password' => 'require',
        ], [
            'name.require'     => '名称不能为空',
            'type.require'     => '数据库类型不能为空',
            'host.require'     => '连接地址不能为空',
            'port.require'     => '端口不能为空',
            'dbname.require'   => '数据库名不能为空',
            'username.require' => '用户名不能为空',
            'password.require' => '密码不能为空',
        ]);
        $dataModel = Model::find($id);
        if (empty($dataModel) || $dataModel->delete_time != 0) {
            return $this->error('数据源信息不存在');
        }
        $data   = [
            'code'        => $params['code'],
            'name'        => $params['name'],
            'type'        => $params['type'],
            'host'        => $params['host'],
            'port'        => $params['port'],
            'dbname'      => $params['dbname'],
            'username'    => $params['username'],
            'password'    => $params['password'],
            'charset'     => $params['charset'],
            'remark'      => $params['remark'],
            'update_time' => $request->time(),
        ];
        $result = $dataModel->save($data);
        if (!$result) {
            return $this->error();
        }
        return $this->success();
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $dataModel = Model::find($id);
        if (!$dataModel || $dataModel->delete_time != 0) {
            return $this->error('您所要删除的信息不存在！');
        }
        $data   = [
            'id'          => $id,
            'delete_time' => time(),
        ];
        $result = $dataModel->save($data);
        if (!$result) {
            return $this->error();
        }
        return $this->success();
    }


    /**
     * 连接测试
     */
    public function testLink(Request $request)
    {
        $params = $request->param();
        $this->validate($params, [
            'host'     => 'require',
            'username' => 'require',
            'port'     => 'require|number',
            'type'     => 'require|in:mysql,oracle,sqlsrv',
        ], [
            'host.require'     => '主机名或ip不能为空！',
//            'host.activeUrl' => '主机名或ip不合法！',
            'username.require' => '用户名不能为空！',
            'port.number'      => '端口号只能是数字！',
            'port.require'     => '端口号不能为空！',
            'type.require'     => '数据库类型不能为空！',
            'type.in'          => '暂不支持该类型数据库！',
        ]);
        ['type' => $type, 'host' => $host, 'port' => $port, 'username' => $username, 'password' => $password,'dbname'=>$dbname] = $params;
        //判断tp框架是否支持此数据库
        $class = '\\think\\db\\connector\\' . ucfirst($type);
        if (!class_exists($class)) {
            return $this->error('暂不支持该类型数据库');
        }
        $dsn = "{$type}:host={$host};port={$port};dbname={$dbname}";
        try {
            new PDO($dsn, $username, $password);
            return $this->success('连接成功');
        } catch (PDOException $e) {
            return $this->error('连接失败');
        }
    }
}
